import { useEffect, useState } from "react";
import { request } from "src/request";
import { Category } from "./useCategories";
import { MixIngredient } from "./useMixIngredients";

export type Food = {
  id?: string;
  name: string;
  image?: string;
  cid?: string;
  category?: Category;
  mixIngredients?: MixIngredient[];
}

export function useFoods(cateId?: string): [Food[], () => Promise<void>, boolean] {
  const [foods, setFoods] = useState<Food[]>([]);
  const [loading, setLoading] = useState(false);

  const fetchFoods = async () => {
    setLoading(true);
    try {
      const response = await request.get('/food', cateId ? { cid: cateId } : undefined);
      setFoods(response.data as Food[]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchFoods();
  }, []);

  return [foods, fetchFoods, loading];
}

export function useFoodMixIngredients(id?: string) {
  const [foodWithMixIngredients, setFoodWithMixIngredients] = useState<Food>();
  const [loading, setLoading] = useState(false);

  const fetchFoodMixIngredients = async () => {
    setLoading(true);
    try {
      const response = await request.get(`/food/${id}/mix-ingredients`);
      setFoodWithMixIngredients(response.data);
    } finally {
      setLoading(false);
    }
  };

  const setFoodMixIngredients = (mixIngredients: MixIngredient[]) => {
    setFoodWithMixIngredients((food) => ({
      ...food,
      mixIngredients,
    }));
  }

  useEffect(() => {
    fetchFoodMixIngredients();
  }, []);

  return {foodWithMixIngredients, fetchFoodMixIngredients, loading, setFoodMixIngredients, setFoodWithMixIngredients};
}

export async function saveFoodMixIngredients(id: string, ids: string[]) {
  const response = await request.post(`/food/${id}/mix-ingredients`, ids);
  return response.data;
}
